import { generator } from 'jm-dynamic-router'
import Layout from '@/body.vue'
const rootRouter = {
	key: '',
	name: 'index',
	path: '/',
	component: Layout,
	redirect: '/home',
	meta: {
		title: '首页'
	},
	children: []
}

const notFoundRouter = {
	path: '*',
	component: {
		render(h) {
			return h('h1', 'notFoundRouter')
		}
	},
	hidden: true
}

export const generatorDynamicRouter = () => {
	return new Promise((resolve, reject) => {
		fetch(`http://localhost:8080/tree.json`).then(res => res.json())
			.then(res => {
				if (res.code === 200) {
					const routers = generator(res.data)
					const item = res.data.find(item => item.component === 'HomeNew')
					const menuNav = []
					rootRouter.children = routers
					if (!item && routers.length) {
						try {
							const parent = routers.at(0)
							const children = parent['children']
							if (children && children.length) {
								console.log('重定向地址: ' + children.at(0).path)
								rootRouter.redirect = children.at(0).path
							}
						} catch (error) {
							console.log(error)
						}
					} else {
            rootRouter.redirect = '/home'
          }
					menuNav.push(rootRouter)
					menuNav.push(notFoundRouter)
					resolve(menuNav)
				}
			})
			.catch(err => {
				reject(err)
			})
	})
}


export default {
	state: {
		addRouters: [],
		menus: []
	},
	mutations: {
		SET_ROUTERS(state, addRouters) {
			state.addRouters = addRouters
		},
		SET_MENUS(state, menus) {
			state.menus = menus
		}
	},
	actions: {
		GenerateRoutes({ commit }) {
			return new Promise(resolve => {
				generatorDynamicRouter().then(routers => {
					commit('SET_ROUTERS', routers)
					commit('SET_MENUS', routers.at(0)?.children)
					resolve()
				})
			})
		},
		ResetRouter({ commit }) {
			commit('SET_ROUTERS', [])
      commit('SET_MENUS', [])
		}
	}
}
